package puzzle.helper;


import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import javax.swing.JComponent;
import java.awt.Graphics;
import java.awt.Dimension;
import java.awt.image.BufferedImage;


// Paints a given image (rescaled if requested).
public class PhotoRescaled extends JComponent {
    
    private BufferedImage image;
    private double ratio;
    
    public PhotoRescaled(String imagePath) {        
        this(imagePath, 0, 0);      
    }
    
    public PhotoRescaled(String imagePath, int width, int height) {  
        
        try {
            image = ImageIO.read(new File(imagePath));
        } catch (IOException ioe) {
            System.out.println("Chosen file does not exist \n" + ioe.getMessage());
        }
        
        if ( width==0 && height==0 ) {
            ratio = 1;
        } else {
            double widthRatio = 1;        
            if( image.getWidth()>width ) {
                widthRatio = (double)width/image.getWidth();
            }
        
            double heightRatio = 1;
            if (image.getHeight()>height) {
                heightRatio = (double)height/image.getHeight();
            }
        
            ratio = Math.min(widthRatio, heightRatio); 
        }
                
        Dimension dimension = new Dimension( (int)( image.getWidth()*ratio ), (int)( image.getHeight()*ratio ) );
	setPreferredSize(dimension);
        
    }   
    
    
    @Override
    public void paintComponent(Graphics g){
        g.drawImage(image, 0, 0, (int)( image.getWidth(null)*ratio ), (int)( image.getHeight(null)*ratio ),
                    0 , 0, image.getWidth(null), image.getHeight(null), this);
    }
    
    
}
